/* Author(s):
 *   Ben Brewer (ben.brewer@codethink.co.uk)
 *
 * Copyright (c) 2013 Codethink (http://www.codethink.co.uk)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <ctype.h>

#include <ogt/arch.h>
#include <ogt/asm.h>
#include <ogt/binary.h>

static void* readfile(const char* path, unsigned* size)
{
	FILE* fp = fopen(path, "rb");
	if (!fp) return NULL;

	if (fseek(fp, 0, SEEK_END) != 0)
	{
		fclose(fp);
		return NULL;
	}
	long fsize = ftell(fp);
	if ((fsize <= 0)
		|| (fseek(fp, 0, SEEK_SET) != 0))
	{
		fclose(fp);
		return NULL;
	}

	void* data = malloc(fsize);
	if (!data)
	{
		fclose(fp);
		return NULL;
	}
	
	if (fread(data, fsize, 1, fp) != 1)
	{
		fclose(fp);
		free(data);
		return NULL;
	}

	fclose(fp);
	if (size)
		*size = (unsigned)fsize;
	return data;
}



int main(int argc, char** argv)
{
	const ogt_arch_t* arch = ogt_arch_lima_t600;
	ogt_asm_syntax_e syntax
		= ogt_asm_syntax_explicit;
	ogt_asm_type_e type = ogt_asm_type_fragment;

	uint32_t* code = NULL;
	unsigned  size = 0;
	int offset = atoi(argv[2]);

	code = readfile(argv[1], &size);
	code += offset;
	size -= offset;

	if (!ogt_arch_disassemble(
		arch, code, size, NULL, type, syntax, 1))
	{
		fprintf(stderr, "Error: Failed to disassemble shader.\n");
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
